<?php

use think\migration\Migrator;
use think\migration\db\Column;

class AddRelationFieldsToCustomerTable extends Migrator
{
    /**
     * 执行迁移
     * 为客户表添加关联字段，实现客户关联关系管理
     */
    public function up()
    {
        // 添加字段
        $table = $this->table('customer');
        
        // 检查字段是否已存在
        if (!$table->hasColumn('group_code')) {
            $table->addColumn('group_code', 'string', [
                'limit' => 32,
                'default' => '',
                'null' => false,
                'comment' => '客户关联唯一代码，相同代码表示关联客户'
            ]);
        }
        
        if (!$table->hasColumn('is_primary')) {
            $table->addColumn('is_primary', 'boolean', [
                'default' => 0,
                'null' => false,
                'comment' => '是否为主企业：0否，1是'
            ]);
        }
        
        if (!$table->hasColumn('controller_name')) {
            $table->addColumn('controller_name', 'string', [
                'limit' => 255,
                'default' => '',
                'null' => false,
                'comment' => '实控人/老板名称'
            ]);
        }
        
        if (!$table->hasColumn('relation_desc')) {
            $table->addColumn('relation_desc', 'string', [
                'limit' => 255,
                'default' => '',
                'null' => false,
                'comment' => '与主企业的关联描述'
            ]);
        }
        
        $table->update();
        
        // 添加索引
        if (!$table->hasIndex('idx_group_code')) {
            $table->addIndex(['group_code'], [
                'name' => 'idx_group_code'
            ]);
        }
        
        $table->save();
        
        $this->output->writeln('客户表关联字段添加成功');
    }

    /**
     * 回滚迁移
     */
    public function down()
    {
        $table = $this->table('customer');
        
        // 删除索引
        if ($table->hasIndex('idx_group_code')) {
            $table->removeIndex(['group_code'], [
                'name' => 'idx_group_code'
            ]);
        }
        
        // 删除字段
        if ($table->hasColumn('relation_desc')) {
            $table->removeColumn('relation_desc');
        }
        
        if ($table->hasColumn('controller_name')) {
            $table->removeColumn('controller_name');
        }
        
        if ($table->hasColumn('is_primary')) {
            $table->removeColumn('is_primary');
        }
        
        if ($table->hasColumn('group_code')) {
            $table->removeColumn('group_code');
        }
        
        $table->save();
        
        $this->output->writeln('客户表关联字段已回滚');
    }
}